# logger_setup.py

# -*- coding: utf-8 -*-

import os

os.system('pip install logging -i https://pypi.tuna.tsinghua.edu.cn/simple')

import logging
from logging.handlers import RotatingFileHandler
import os
import sys
import threading

# 创建一个标志，确保 setup_logger 只执行一次
_logger_setup_done = False
_logger_lock = threading.Lock()


def setup_logger(log_file):
    global _logger_setup_done

    with _logger_lock:
        if _logger_setup_done:
            return

        # 创建日志目录（如果不存在）
        log_directory = os.path.dirname(log_file)
        if not os.path.exists(log_directory):
            os.makedirs(log_directory)

        # 创建日志记录器
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        # 创建一个 RotatingFileHandler
        handler = RotatingFileHandler(log_file, maxBytes=5 * 1024 * 1024, backupCount=3)  # 5MB, 保留3个备份文件
        handler.setLevel(logging.DEBUG)

        # 设置日志格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)

        # 添加处理器到日志记录器
        logger.addHandler(handler)

        # 创建一个流处理器来输出日志到控制台
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

        # 重定向 stdout 和 stderr
        class StreamToLogger:
            def __init__(self, logger, level):
                self.logger = logger
                self.level = level

            def write(self, message):
                if message.strip():
                    self.logger.log(self.level, message.strip())

            def flush(self):
                pass

            def isatty(self):
                return False

        sys.stdout = StreamToLogger(logger, logging.INFO)
        # sys.stdout = StreamToLogger(logger, logging.ERROR)

        logger.info("Logger successfully configured.")

        _logger_setup_done = True
